<template>
  <div class="toolbar">
    <el-input
      v-model="search.name"
      style="width: 240px"
      placeholder="请输入姓名"
      clearable
      :prefix-icon="Search"
      @change="onSearchChange"
    />
  </div>

  <div class="btn-group">
    <el-button-group>
      <el-button type="primary" :icon="Plus" @click="plusRow">添加</el-button>
      <el-button type="danger" :icon="Delete" @click="deleteAll"
        >删除所选</el-button
      >
    </el-button-group>
  </div>

  <el-table
    ref="tableRef"
    @sort-change="sortChange"
    :data="tableData"
    style="width: 100%"
  >
    <el-table-column type="selection" width="55" />

    <el-table-column fixed label="创建日期" width="150">
      <template #default="{ row }">
        {{ getFormatTime(row.createTime) }}
      </template>
    </el-table-column>
    <el-table-column sortable prop="name" label="姓名" width="120" />
    <el-table-column sortable prop="mobile" label="电话" width="120" />
    <el-table-column sortable prop="description" label="详细地址" width="320" />
    <el-table-column prop="isDefault" label="是否默认" width="120">
      <template #default="scope">
        <el-switch
          v-model="scope.row.isDefault"
          active-value="1"
          inactive-value="0"
          @click="switchChange(scope.row)"
        />
      </template>
    </el-table-column>
    <el-table-column prop="provinceName" label="省份" width="120">
    </el-table-column>

    <el-table-column fixed label="更新日期" width="120">
      <template #default="{ row }">
        {{ getFormatTime(row.updateTime) }}
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="120">
      <template #default="scope">
        <el-button
          link
          type="primary"
          size="small"
          @click="handleAddressEdit(scope.row)"
        >
          编辑
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          @click="handleAddressDelete(scope.row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>


  <!-- 编辑按钮 -->
  <el-dialog
    style="width: 500px; border-radius: 10px"
    v-model="addressEditDialog.isVisible"
    :title="addressEditDialog.title"
    align-center
  >
    <el-form label-width="100px" label-position="left">
      <el-form-item label="姓名">
        <el-input v-model="addressDetail.name" />
      </el-form-item>
      <el-form-item label="电话号码">
        <el-input v-model="addressDetail.mobile" />
      </el-form-item>
      <el-form-item label="所在省份">
        <el-select
          v-model="optionValue"
          :placeholder="addressDetail.provinceName"
          size="large"
          style="height: 30px"
        >
          <el-option
            v-for="item in provineOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="详细地址">
        <el-input v-model="addressDetail.description" />
      </el-form-item>

      <el-form-item label="默认地址">
        <span>否&nbsp;</span>
        <el-switch
          v-model="addressDetail.isDefault"
          active-value="1"
          inactive-value="0"
        />
        <span>&nbsp;是</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveEdit()"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加按钮 -->
  <el-dialog
    style="width: 550px"
    v-model="plusAndEditDialog.isVisible"
    :title="plusAndEditDialog.title"
    align-center
  >
    <el-form label-width="100px" label-position="left">
      <el-form-item label="姓名">
        <el-input v-model="addAddressDetail.name" />
      </el-form-item>
      <el-form-item label="电话号码">
        <el-input v-model="addAddressDetail.mobile" />
      </el-form-item>
      <el-form-item label="所在省份">
        <el-select
          v-model="optionValue"
          placeholder="请选择省份"
          size="large"
          style="height: 30px"
        >
          <el-option
            v-for="item in provineOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="详细地址">
        <el-input v-model="addAddressDetail.description" />
      </el-form-item>

      <el-form-item label="默认地址">
        <span>否&nbsp;</span>
        <el-switch
          v-model="addAddressDetail.isDefault"
          active-value="1"
          inactive-value="0"
        />
        <span>&nbsp;是</span>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <!-- <el-button @click="centerDialogVisible = false">Cancel</el-button> -->
        <el-button type="primary" @click="saveAdd"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>

  <div class="pagination">
    <el-pagination
      :page-sizes="[2, 5, 20, 40, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      :default-page-size="pagination.size"
      @change="onPaginationChange"
    />
  </div>
</template>

<script setup>
import {
  addressPage,
  addressDeleteByUserId,
  addressDeleteBatch,
  addressAdd,
  addressEdit,
} from "@/apis/user/address";
import { reactive, onMounted, ref, warn } from "vue";
import { useRouter } from "vue-router";
import { getFormatTime } from "@/apis/utility";
import { provincePage, provinceGetById } from "@/apis/province";
import { Delete, Edit, Plus, Search } from "@element-plus/icons-vue";


const router = useRouter();

// 数据
const tableData = ref([]);

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});

// 搜索输入框搜索条件
const search = reactive({
  id: "",
  name: "",
  mobile: "",
  description: "",
  isDefault: "",
  createTime: "",
  userId: "",
});

// 过滤对应的条件
const filter = ref({});

// 存储排序字段
const orders = reactive({
  column: "id",
  isAsc: true,
});

// 地址获取数据
const getAddress = async () => {
  try {
    const result = await addressPage(
      {
        filter: filter,
        search: search,
        orders: [orders],
      },
      pagination.page,
      pagination.size
    );
    tableData.value = result.data.records;
    pagination.total = result.data.total;
    console.log(tableData.value);
  } catch (error) {
    console.error(error);
  }
};

// 编辑地址提交函数
const editAddressEdit = async (row) => {
  try {
    const result = await addressEdit(row);
    if (result != undefined) {
      addressEditDialog.isVisible = false;
    }
  } catch (error) {
  }
};

// 添加地址提交函数
const addAddressAdd = async (row) => {
  try {
    const result = await addressAdd(row);
    if (result != undefined) {
      console.log(result);
      plusAndEditDialog.isVisible = false;
    }
  } catch (error) {
    console.error(error);
  }
};

// 根据ID删除地址提交函数
const deleteByIdAddressEdit = async (id) => {
  try {
    // console.log(row);
    const result = await addressDeleteByUserId(id);
    // console.log(result);
    getAddress();

  } catch (error) {
    console.error();
  }
};
// 批量删除地址提交函数
const deleteBatchAddressEdit = async (row) => {
  try {
    // console.log(row);
    const result = await addressDeleteBatch(row);
    console.log(result);
  } catch (error) {
    console.error();
  }
};

// 分页改变函数
const onPaginationChange = async (currentPage, pageSize) => {
  pagination.page = currentPage;
  pagination.size = pageSize;
  await getAddress();
};

// 页面加载时执行
onMounted(async () => {
  await getAddress();
});

// 触发状态开关
const switchChange = async (row) => {
  // console.log(row);
  try {
    await editAddressEdit(row);
    getAddress();
  } catch (error) {
    console.error(error);
  }
};



// 编辑地址信息
/**
 * 地址编辑对话框
 */
const addressEditDialog = reactive({
  isVisible: false,
  title: "用户地址",
});
// 编辑地址数据
const addressDetail = reactive({});
// 编辑地址触发函数
const handleAddressEdit = async (row) => {
  optionValue.value = ""
  Object.assign(addressDetail, row);
  await getProvincePage();
  try {
    await editAddressEdit(row);
    addressEditDialog.isVisible = true;
  } catch (error) {
    console.error(error);
  }
};
// 触发地址保存
const saveEdit = async () => {
  if(optionValue.value) addressDetail.provinceId = optionValue.value;
  await editAddressEdit(addressDetail);
  getAddress()
};



// 获取省份
const provincePagination = reactive({
  page: 1,
  size: 34,
});
const getProvincePage = async () => {
  try {
    const result = await provincePage(
      {},
      provincePagination.page,
      provincePagination.size
    );
    provineOptions.value = result.data.records;
  } catch (error) {
    console.error(error);
  }
};

// 多选框默认值
const optionValue = ref("");
// 多选框取值
const provineOptions = ref([]);

// 删除地址触发函数
const handleAddressDelete = async (id) => {
  // console.log(id);
  try {
    await deleteByIdAddressEdit(id);
  } catch (error) {
    console.error(error);
  }
};

// 获取表格组件引用对象： 前提在表格上加上 ref="tableRef"
const tableRef = ref();

// 搜索输入框对应的触发事件
const onSearchChange = async () => {
  await getAddress();
};

// 删除全部选中行
const deleteAll = async () => {
  const selectionRows = tableRef.value.getSelectionRows();
  console.log(selectionRows);
  const ids = selectionRows.map((row) => {
    return row.id;
  });

  await addressDeleteBatch(ids).then((result) => {
    console.log(result);
  });
  getAddress();
};

/**
 * 表格排序函数
 * @param {*} column 当前列对
 * @param {*} prop 当前字段
 * @param {*} order 当前排序方式
 */
const sortChange = ({ prop, order }) => {
  console.log(prop, order);
  // orders.column = "CAST(like_count AS UNSIGNED)";
  Object.assign(orders, {
    column: `CAST(${prop} AS UNSIGNED)`,
    isAsc: order === "ascending",
  });
  getAddress();
};


// 添加地址数据
const addAddressDetail = reactive({});

/**
 * 添加和修改的对话框
 */
const plusAndEditDialog = reactive({
  isVisible: false,
  title: "添加新地址",
});

// 触发地址保存
const saveAdd = async () => {
  addAddressDetail.provinceId = optionValue.value;
  await addAddressAdd(addAddressDetail);
  getAddress();
  // console.log(result);
};

/**
 * 添加一行数据
 */
const plusRow = async () => {
  Object.assign(addAddressDetail, ...Object.keys(addAddressDetail).map(key => ({ [key]: null })));  console.warn(addAddressDetail)
  await getProvincePage();
  plusAndEditDialog.isVisible = true;
  getAddress();
};
</script>




<style lang="less" scoped>
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.toolbar {
  padding-bottom: 20px;
  display: flex;
}

.filter {
  display: flex;
  margin-bottom: 20px;
}
.el-input,
.el-select {
  max-width: 250px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
}
.el-table {
  height: calc(100vh - 265px);
}
.el-form {
  padding: 20px 40px;
}
</style>
